<template>
  <div class="ai-consultation-page">
    <div class="page-header">
      <h1>智能咨询</h1>
      <p>AI法律问答，快速获得专业解答</p>
    </div>

    <div class="consultation-container">
      <!-- 左侧：咨询界面 -->
      <div class="chat-section">
        <div class="chat-header">
          <el-icon><Robot /></el-icon>
          <span>法律AI助手</span>
          <el-button type="link" @click="clearChat" class="clear-btn">
            <el-icon><Delete /></el-icon>
            清空对话
          </el-button>
        </div>

        <div class="chat-messages" ref="messagesRef">
          <div v-if="messages.length === 0" class="welcome-message">
            <el-icon class="welcome-icon"><ChatDotRound /></el-icon>
            <h3>欢迎使用智能法律咨询</h3>
            <p>您可以向我咨询任何法律问题，我会为您提供专业的解答</p>
            <div class="quick-questions">
              <h4>常见问题：</h4>
              <el-button
                v-for="question in quickQuestions"
                :key="question"
                type="link"
                @click="sendQuickQuestion(question)"
                class="quick-question-btn"
              >
                {{ question }}
              </el-button>
            </div>
          </div>

          <div 
            v-for="message in messages" 
            :key="message.id"
            class="message-item"
            :class="{ 'user-message': message.type === 'user', 'ai-message': message.type === 'ai' }"
          >
            <div class="message-avatar">
              <el-icon v-if="message.type === 'user'"><User /></el-icon>
              <el-icon v-else><Robot /></el-icon>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="message.content"></div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>

          <div v-if="isTyping" class="message-item ai-message">
            <div class="message-avatar">
              <el-icon><Robot /></el-icon>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入您的法律问题..."
            @keydown.ctrl.enter="sendMessage"
            :disabled="isTyping"
          />
          <div class="input-actions">
            <span class="input-tip">Ctrl + Enter 发送</span>
            <el-button 
              type="primary" 
              @click="sendMessage"
              :loading="isTyping"
              :disabled="!inputMessage.trim()"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>

      <!-- 右侧：功能面板 -->
      <div class="feature-panel">
        <div class="panel-card">
          <h3>咨询统计</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-number">{{ consultationStats.total }}</div>
              <div class="stat-label">总咨询次数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ consultationStats.today }}</div>
              <div class="stat-label">今日咨询</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ consultationStats.satisfaction }}%</div>
              <div class="stat-label">满意度</div>
            </div>
          </div>
        </div>

        <div class="panel-card">
          <h3>热门问题</h3>
          <div class="hot-questions">
            <div 
              v-for="question in hotQuestions" 
              :key="question.id"
              class="hot-question-item"
              @click="sendQuickQuestion(question.content)"
            >
              <div class="question-text">{{ question.content }}</div>
              <div class="question-count">{{ question.count }}次咨询</div>
            </div>
          </div>
        </div>

        <div class="panel-card">
          <h3>专业领域</h3>
          <div class="expertise-areas">
            <el-tag 
              v-for="area in expertiseAreas" 
              :key="area"
              class="area-tag"
              @click="sendQuickQuestion(`请介绍${area}相关的法律知识`)"
            >
              {{ area }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

interface Message {
  id: string
  type: 'user' | 'ai'
  content: string
  timestamp: number
}

const messages = ref<Message[]>([])
const inputMessage = ref('')
const isTyping = ref(false)
const messagesRef = ref<HTMLElement>()

// 快速问题
const quickQuestions = [
  '劳动合同纠纷如何处理？',
  '房屋买卖合同注意事项',
  '公司股权转让流程',
  '知识产权保护措施'
]

// 热门问题
const hotQuestions = ref([
  { id: '1', content: '劳动合同违约金标准', count: 156 },
  { id: '2', content: '房产过户手续流程', count: 142 },
  { id: '3', content: '公司注册资本要求', count: 128 },
  { id: '4', content: '商标注册申请条件', count: 115 }
])

// 专业领域
const expertiseAreas = [
  '劳动法', '合同法', '公司法', '知识产权法',
  '房地产法', '刑法', '民法', '行政法'
]

// 咨询统计
const consultationStats = ref({
  total: 1248,
  today: 23,
  satisfaction: 96
})

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isTyping.value) return

  const userMessage: Message = {
    id: Date.now().toString(),
    type: 'user',
    content: inputMessage.value,
    timestamp: Date.now()
  }

  messages.value.push(userMessage)
  const question = inputMessage.value
  inputMessage.value = ''

  await scrollToBottom()

  // 模拟AI回复
  isTyping.value = true
  setTimeout(async () => {
    const aiResponse = generateAIResponse(question)
    const aiMessage: Message = {
      id: (Date.now() + 1).toString(),
      type: 'ai',
      content: aiResponse,
      timestamp: Date.now()
    }

    messages.value.push(aiMessage)
    isTyping.value = false
    await scrollToBottom()
  }, 2000)
}

// 发送快速问题
const sendQuickQuestion = (question: string) => {
  inputMessage.value = question
  sendMessage()
}

// 生成AI回复
const generateAIResponse = (question: string): string => {
  const responses = {
    '劳动': `
      <p><strong>关于劳动法相关问题：</strong></p>
      <p>1. <strong>劳动合同</strong>：应当明确工作内容、工作地点、工作时间、劳动报酬等基本条款</p>
      <p>2. <strong>违约金</strong>：只有在培训费用和竞业限制两种情况下才能约定违约金</p>
      <p>3. <strong>解除合同</strong>：需要符合法定条件，用人单位不得随意解除</p>
      <p>4. <strong>经济补偿</strong>：按工作年限计算，每满一年支付一个月工资</p>
      <p><em>建议：如有具体争议，请提供详细情况以便给出更准确的建议。</em></p>
    `,
    '合同': `
      <p><strong>合同法律要点：</strong></p>
      <p>1. <strong>合同成立</strong>：要约和承诺一致即可成立</p>
      <p>2. <strong>合同效力</strong>：需要主体适格、意思表示真实、不违法</p>
      <p>3. <strong>违约责任</strong>：包括继续履行、赔偿损失、支付违约金等</p>
      <p>4. <strong>合同解除</strong>：协商解除或法定解除</p>
      <p><em>提醒：重要合同建议请专业律师审查。</em></p>
    `,
    '公司': `
      <p><strong>公司法相关规定：</strong></p>
      <p>1. <strong>公司设立</strong>：需要符合法定条件和程序</p>
      <p>2. <strong>股权转让</strong>：有限公司需要其他股东同意</p>
      <p>3. <strong>公司治理</strong>：股东会、董事会、监事会职责分工</p>
      <p>4. <strong>法律责任</strong>：股东、董事、监事的责任界限</p>
      <p><em>注意：公司事务复杂，建议咨询专业律师。</em></p>
    `,
    '知识产权': `
      <p><strong>知识产权保护：</strong></p>
      <p>1. <strong>专利保护</strong>：发明、实用新型、外观设计</p>
      <p>2. <strong>商标保护</strong>：注册商标享有专用权</p>
      <p>3. <strong>著作权</strong>：作品完成即享有著作权</p>
      <p>4. <strong>商业秘密</strong>：采取保密措施的技术信息和经营信息</p>
      <p><em>建议：及时申请保护，建立完善的知识产权管理制度。</em></p>
    `
  }

  for (const [key, response] of Object.entries(responses)) {
    if (question.includes(key)) {
      return response
    }
  }

  return `
    <p><strong>感谢您的咨询！</strong></p>
    <p>我已经收到您的问题："${question}"</p>
    <p>这是一个很好的法律问题。根据相关法律规定，我建议您：</p>
    <p>1. 收集相关证据材料</p>
    <p>2. 了解适用的法律条文</p>
    <p>3. 评估法律风险和可能的解决方案</p>
    <p>4. 必要时寻求专业律师的帮助</p>
    <p><em>如需更详细的解答，请提供更多具体信息。</em></p>
  `
}

// 清空对话
const clearChat = () => {
  messages.value = []
  ElMessage.success('对话已清空')
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

onMounted(() => {
  // 模拟欢迎消息
  setTimeout(() => {
    consultationStats.value.today++
  }, 1000)
})
</script>

<style lang="scss" scoped>
.ai-consultation-page {
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;

  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 24px;
    }
    
    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }

  .consultation-container {
    flex: 1;
    display: flex;
    gap: 20px;
    min-height: 0;

    .chat-section {
      flex: 1;
      display: flex;
      flex-direction: column;
      background: #fff;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      min-height: 0;

      .chat-header {
        padding: 16px 20px;
        border-bottom: 1px solid #e4e7ed;
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          font-size: 20px;
          color: #409eff;
        }
        
        span {
          font-weight: 600;
          color: #303133;
        }
        
        .clear-btn {
          margin-left: auto;
          color: #909399;
        }
      }

      .chat-messages {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
        min-height: 0;

        .welcome-message {
          text-align: center;
          padding: 40px 20px;
          
          .welcome-icon {
            font-size: 48px;
            color: #409eff;
            margin-bottom: 16px;
          }
          
          h3 {
            margin: 0 0 8px 0;
            color: #303133;
          }
          
          p {
            margin: 0 0 24px 0;
            color: #606266;
          }
          
          .quick-questions {
            text-align: left;
            
            h4 {
              margin: 0 0 12px 0;
              color: #303133;
              font-size: 14px;
            }
            
            .quick-question-btn {
              display: block;
              margin: 8px 0;
              text-align: left;
              color: #409eff;
              
              &:hover {
                background: #f0f9ff;
              }
            }
          }
        }

        .message-item {
          display: flex;
          margin-bottom: 20px;
          
          &.user-message {
            flex-direction: row-reverse;
            
            .message-content {
              background: #409eff;
              color: #fff;
              margin-right: 12px;
            }
          }
          
          &.ai-message {
            .message-content {
              background: #f5f7fa;
              color: #303133;
              margin-left: 12px;
            }
          }
          
          .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e4e7ed;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            
            .el-icon {
              font-size: 18px;
              color: #606266;
            }
          }
          
          .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
            
            .message-text {
              line-height: 1.5;
              
              :deep(p) {
                margin: 8px 0;
                
                &:first-child {
                  margin-top: 0;
                }
                
                &:last-child {
                  margin-bottom: 0;
                }
              }
              
              :deep(strong) {
                font-weight: 600;
              }
              
              :deep(em) {
                font-style: italic;
                opacity: 0.8;
              }
            }
            
            .message-time {
              font-size: 12px;
              opacity: 0.6;
              margin-top: 8px;
            }
          }
        }

        .typing-indicator {
          display: flex;
          gap: 4px;
          
          span {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #409eff;
            animation: typing 1.4s infinite ease-in-out;
            
            &:nth-child(1) { animation-delay: -0.32s; }
            &:nth-child(2) { animation-delay: -0.16s; }
          }
        }
      }

      .chat-input {
        padding: 20px;
        border-top: 1px solid #e4e7ed;
        
        .input-actions {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 12px;
          
          .input-tip {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }

    .feature-panel {
      width: 300px;
      display: flex;
      flex-direction: column;
      gap: 20px;

      .panel-card {
        background: #fff;
        border-radius: 8px;
        border: 1px solid #e4e7ed;
        padding: 20px;
        
        h3 {
          margin: 0 0 16px 0;
          color: #303133;
          font-size: 16px;
        }
        
        .stats-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 16px;
          
          .stat-item {
            text-align: center;
            
            .stat-number {
              font-size: 24px;
              font-weight: 600;
              color: #409eff;
              margin-bottom: 4px;
            }
            
            .stat-label {
              font-size: 12px;
              color: #909399;
            }
          }
        }
        
        .hot-questions {
          .hot-question-item {
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: all 0.3s;
            
            &:last-child {
              border-bottom: none;
            }
            
            &:hover {
              background: #f8f9fa;
              margin: 0 -20px;
              padding-left: 20px;
              padding-right: 20px;
            }
            
            .question-text {
              font-size: 14px;
              color: #303133;
              margin-bottom: 4px;
            }
            
            .question-count {
              font-size: 12px;
              color: #909399;
            }
          }
        }
        
        .expertise-areas {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          
          .area-tag {
            cursor: pointer;
            transition: all 0.3s;
            
            &:hover {
              background: #409eff;
              color: #fff;
            }
          }
        }
      }
    }
  }
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

@media (max-width: 768px) {
  .ai-consultation-page {
    .consultation-container {
      flex-direction: column;
      
      .feature-panel {
        width: 100%;
        flex-direction: row;
        overflow-x: auto;
        
        .panel-card {
          min-width: 250px;
        }
      }
    }
  }
}
</style>
